package cn.com.ghy.android.widget.visit;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import cn.com.ghy.android.widget.R;

/**
 * @软件著作权:金红叶纸业集团有限公司
 * @系统名称:SFA系统
 * @Description:自定义拍照功能,参照李宁/<android-ophone手机应用开发教程>
 * @author wuz @date 2011-6-7 09:18:09
 * @版本历史:v1.0
 * @Copyright:Copyright (c) 2011-2012
 */

public class CameraPreview extends Activity implements Callback, OnClickListener {
	SurfaceView mySurfaceView = null;
	SurfaceHolder holder = null;
	Camera myCamera = null;
	boolean isClicked = false;
	PictureCallback jpeg = new PictureCallback() {
		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			getIntent().putExtra("data", data);
			setResult(Activity.RESULT_OK, getIntent());
			camera.stopPreview();
			camera = null;
			finish();
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		setContentView(R.layout.camera_preview);
		mySurfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
		holder = mySurfaceView.getHolder();
		holder.addCallback(this);
		holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		mySurfaceView.setOnClickListener(this);
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		Camera.Parameters params = myCamera.getParameters();
		params.setPictureFormat(PixelFormat.JPEG);
		params.setPictureSize(640, 480);
		myCamera.setParameters(params);
		myCamera.startPreview();
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (myCamera == null) {
			try {
				myCamera = Camera.open();
				myCamera.setPreviewDisplay(holder);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		myCamera.stopPreview();
		myCamera.release();
		myCamera = null;

	}

	@Override
	public void onClick(View v) {
		if (!isClicked) {
			Camera.Parameters params = myCamera.getParameters();
			params.setPictureFormat(PixelFormat.JPEG);
			params.set("jpeg-quality", 100);
			myCamera.setParameters(params);
			myCamera.takePicture(null, null, jpeg);
			isClicked = true;
		} else {
			myCamera.startPreview();
			isClicked = false;
		}

	}
}
